package top.lywivan.netty.handler.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author :lyw.ivan
 * @date :Created in 2022/8/14
 * @description : 处理客户端空闲检测的handler，保证可以及时释放资源。IdleStateHandler即可出站，也可入站
 * @version: 1.0
 */
@Slf4j
public class ServerReadIdleHandler extends IdleStateHandler {

    /**
     * 构造方法，分别表示，读写空间多长时，断开连接。0表示不会断开
     * @param readerIdleTimeSeconds
     * @param writerIdleTimeSeconds
     * @param allIdleTimeSeconds
     */
    public ServerReadIdleHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds, TimeUnit.SECONDS);
    }

    /**
     * 断开连接时会调用该方法
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        if(evt==IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT){
            ctx.close();
            log.info("客户端空闲过长未发送消息，断开连接");
            return;
        }
        super.channelIdle(ctx, evt);
    }
}
